package com.example.cheeseerpadmin.sys.controller;

import com.example.cheeseerpadmin.sys.common.ActiverUser;
import com.example.cheeseerpadmin.sys.common.ResultObj;
import com.example.cheeseerpadmin.sys.entity.SysLoginfo;
import com.example.cheeseerpadmin.sys.service.SysLoginfoService;
import com.example.cheeseerpadmin.sys.vo.LoginfoVo;
import org.apache.catalina.connector.Request;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.cheeseerpadmin.sys.common.WebUtils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Date;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    public SysLoginfoService sysLoginfoService;

    @RequestMapping("/login")
    public ResultObj login(String loginname,String pwd) {
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token = new UsernamePasswordToken(loginname, pwd);
        try{
            //获取到token以后，将这个token传到UserRealm当中去查询对应的用户信息
            //然后拿到用户信息以后再和需要登录的用户进行对比
            subject.login(token);

            //而这下面的操作应该就是给session赋值，便于之后用户退出登录销毁session
            ActiverUser activerUser = (ActiverUser)subject.getPrincipal();
//            WebUtils.setSessionAttribute(request,"user",activerUser.getUser());
            WebUtils.getSession().setAttribute("user",activerUser.getUser());

            SysLoginfo sysLoginfo = new SysLoginfo();
            sysLoginfo.setLoginname(activerUser.getUser().getName()+"-"+activerUser.getUser().getLoginname());
            sysLoginfo.setLoginip(WebUtils.getRequest().getRemoteAddr());
            sysLoginfo.setLogintime(new Date());
            sysLoginfoService.save(sysLoginfo);

            return ResultObj.LOGIN_SUCCESS;
        }catch (AuthenticationException e){
            e.printStackTrace();
            return ResultObj.LOGIN_ERROR_PASS;
        }
    }
}
